<template>
  <div class="template-edit">
    <div class="edit-header">
      <h3>{{ isEdit ? '编辑病历模板' : '新建病历模板' }}</h3>
      <div class="header-actions">
        <el-button type="primary" @click="handleSave" :loading="saving">
          <el-icon><Check /></el-icon>
          保存模板
        </el-button>
        <el-button @click="handleCancel">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
      </div>
    </div>

    <div class="edit-content">
      <!-- 基本信息 -->
      <el-card class="basic-info-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-form
          ref="basicFormRef"
          :model="formData"
          :rules="basicRules"
          label-width="100px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="模板名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入模板名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="适用科室" prop="department">
                <el-select
                  v-model="formData.department"
                  placeholder="请选择适用科室"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dept in departmentOptions"
                    :key="dept.value"
                    :label="dept.label"
                    :value="dept.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="模板类型" prop="type">
                <el-select
                  v-model="formData.type"
                  placeholder="请选择模板类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="type in templateTypeOptions"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio label="active">启用</el-radio>
                  <el-radio label="inactive">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="模板描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入模板描述信息"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="设为默认">
            <el-switch
              v-model="formData.isDefault"
              active-text="是"
              inactive-text="否"
            />
            <div class="switch-tip">
              设置为该科室的默认模板
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 模板内容编辑 -->
      <el-card class="content-editor-card">
        <template #header>
          <div class="card-header">
            <span>模板内容</span>
            <div class="content-actions">
              <el-button type="text" @click="insertVariable('patient.name')">
                插入患者姓名
              </el-button>
              <el-button type="text" @click="insertVariable('patient.age')">
                插入患者年龄
              </el-button>
              <el-button type="text" @click="insertVariable('current.date')">
                插入当前日期
              </el-button>
              <el-button type="text" @click="showAllVariables = true">
                更多变量
              </el-button>
            </div>
          </div>
        </template>

        <div class="content-editor">
          <!-- 主诉 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>主诉</h4>
              <el-button type="text" @click="clearSection('chiefComplaint')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.chiefComplaint"
              type="textarea"
              :rows="3"
              placeholder="请输入主诉模板内容，可使用变量如：{{patient.name}}患者主诉..."
              resize="vertical"
            />
          </div>

          <!-- 现病史 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>现病史</h4>
              <el-button type="text" @click="clearSection('presentIllness')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.presentIllness"
              type="textarea"
              :rows="4"
              placeholder="请输入现病史模板内容"
              resize="vertical"
            />
          </div>

          <!-- 既往史 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>既往史</h4>
              <el-button type="text" @click="clearSection('pastHistory')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.pastHistory"
              type="textarea"
              :rows="3"
              placeholder="请输入既往史模板内容"
              resize="vertical"
            />
          </div>

          <!-- 过敏史 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>过敏史</h4>
              <el-button type="text" @click="clearSection('allergyHistory')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.allergyHistory"
              type="textarea"
              :rows="2"
              placeholder="请输入过敏史模板内容"
              resize="vertical"
            />
          </div>

          <!-- 体格检查 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>体格检查</h4>
              <el-button type="text" @click="clearSection('physicalExam')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.physicalExam"
              type="textarea"
              :rows="4"
              placeholder="请输入体格检查模板内容"
              resize="vertical"
            />
          </div>

          <!-- 辅助检查 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>辅助检查</h4>
              <el-button type="text" @click="clearSection('labResults')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.labResults"
              type="textarea"
              :rows="3"
              placeholder="请输入辅助检查模板内容"
              resize="vertical"
            />
          </div>

          <!-- 诊断 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>诊断</h4>
              <el-button type="text" @click="clearSection('diagnosis')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.diagnosis"
              type="textarea"
              :rows="3"
              placeholder="请输入诊断模板内容"
              resize="vertical"
            />
          </div>

          <!-- 治疗方案 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>治疗方案</h4>
              <el-button type="text" @click="clearSection('treatmentPlan')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.treatmentPlan"
              type="textarea"
              :rows="4"
              placeholder="请输入治疗方案模板内容"
              resize="vertical"
            />
          </div>

          <!-- 医嘱 -->
          <div class="editor-section">
            <div class="section-header">
              <h4>医嘱</h4>
              <el-button type="text" @click="clearSection('medicalAdvice')">
                清空
              </el-button>
            </div>
            <el-input
              v-model="formData.content.medicalAdvice"
              type="textarea"
              :rows="3"
              placeholder="请输入医嘱模板内容"
              resize="vertical"
            />
          </div>
        </div>
      </el-card>

      <!-- 模板预览 -->
      <el-card class="preview-card">
        <template #header>
          <div class="card-header">
            <span>模板预览</span>
            <el-button type="text" @click="refreshPreview">
              <el-icon><Refresh /></el-icon>
              刷新预览
            </el-button>
          </div>
        </template>
        <div class="preview-content">
          <div class="preview-section" v-if="formData.content.chiefComplaint">
            <h5>主诉</h5>
            <div class="preview-text">{{ formatPreviewText(formData.content.chiefComplaint) }}</div>
          </div>
          
          <div class="preview-section" v-if="formData.content.presentIllness">
            <h5>现病史</h5>
            <div class="preview-text">{{ formatPreviewText(formData.content.presentIllness) }}</div>
          </div>
          
          <div class="preview-section" v-if="formData.content.pastHistory">
            <h5>既往史</h5>
            <div class="preview-text">{{ formatPreviewText(formData.content.pastHistory) }}</div>
          </div>
          
          <div class="preview-section" v-if="formData.content.physicalExam">
            <h5>体格检查</h5>
            <div class="preview-text">{{ formatPreviewText(formData.content.physicalExam) }}</div>
          </div>
          
          <div class="preview-section" v-if="formData.content.diagnosis">
            <h5>诊断</h5>
            <div class="preview-text">{{ formatPreviewText(formData.content.diagnosis) }}</div>
          </div>
          
          <div class="preview-section" v-if="formData.content.treatmentPlan">
            <h5>治疗方案</h5>
            <div class="preview-text">{{ formatPreviewText(formData.content.treatmentPlan) }}</div>
          </div>

          <div v-if="!hasContent" class="empty-preview">
            <el-empty description="暂无模板内容，请在左侧编辑区域添加内容" />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 变量选择对话框 -->
    <el-dialog
      v-model="showAllVariables"
      title="可用变量"
      width="600px"
    >
      <div class="variables-dialog">
        <el-table :data="availableVariables" style="width: 100%">
          <el-table-column prop="name" label="变量名" width="200" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="text" @click="insertVariable(row.variable)">
                插入
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Close, Refresh } from '@element-plus/icons-vue'

const props = defineProps({
  templateData: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['saved', 'cancel'])

// 响应式数据
const saving = ref(false)
const showAllVariables = ref(false)
const basicFormRef = ref()
const currentActiveSection = ref('chiefComplaint')

// 选项数据
const departmentOptions = [
  { label: '内科', value: 'internal' },
  { label: '外科', value: 'surgery' },
  { label: '儿科', value: 'pediatrics' },
  { label: '妇产科', value: 'obstetrics' },
  { label: '眼科', value: 'ophthalmology' },
  { label: '耳鼻喉科', value: 'ent' },
  { label: '皮肤科', value: 'dermatology' },
  { label: '中医科', value: 'tcm' }
]

const templateTypeOptions = [
  { label: '初诊病历', value: 'initial' },
  { label: '复诊病历', value: 'followup' },
  { label: '急诊病历', value: 'emergency' },
  { label: '住院病历', value: 'inpatient' },
  { label: '体检病历', value: 'physical' }
]

// 可用变量
const availableVariables = ref([
  { variable: 'patient.name', name: '患者姓名', description: '患者全名' },
  { variable: 'patient.age', name: '患者年龄', description: '患者当前年龄' },
  { variable: 'patient.gender', name: '患者性别', description: '患者性别' },
  { variable: 'patient.phone', name: '患者电话', description: '患者联系电话' },
  { variable: 'patient.idCard', name: '身份证号', description: '患者身份证号码' },
  { variable: 'current.date', name: '当前日期', description: '系统当前日期' },
  { variable: 'current.time', name: '当前时间', description: '系统当前时间' },
  { variable: 'doctor.name', name: '医生姓名', description: '当前医生姓名' },
  { variable: 'department.name', name: '科室名称', description: '当前科室名称' },
  { variable: 'hospital.name', name: '医院名称', description: '医院全称' }
])

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  department: '',
  type: 'initial',
  status: 'active',
  isDefault: false,
  content: {
    chiefComplaint: '',
    presentIllness: '',
    pastHistory: '',
    allergyHistory: '',
    physicalExam: '',
    labResults: '',
    diagnosis: '',
    treatmentPlan: '',
    medicalAdvice: ''
  }
})

// 验证规则
const basicRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模板名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择适用科室', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ]
}

// 计算属性
const hasContent = computed(() => {
  return Object.values(formData.content).some(value => value && value.trim() !== '')
})

// 方法
const initFormData = () => {
  if (props.isEdit && props.templateData) {
    Object.assign(formData, {
      name: props.templateData.name || '',
      description: props.templateData.description || '',
      department: props.templateData.department || '',
      type: props.templateData.type || 'initial',
      status: props.templateData.status || 'active',
      isDefault: props.templateData.isDefault || false,
      content: {
        chiefComplaint: props.templateData.content?.chiefComplaint || '',
        presentIllness: props.templateData.content?.presentIllness || '',
        pastHistory: props.templateData.content?.pastHistory || '',
        allergyHistory: props.templateData.content?.allergyHistory || '',
        physicalExam: props.templateData.content?.physicalExam || '',
        labResults: props.templateData.content?.labResults || '',
        diagnosis: props.templateData.content?.diagnosis || '',
        treatmentPlan: props.templateData.content?.treatmentPlan || '',
        medicalAdvice: props.templateData.content?.medicalAdvice || ''
      }
    })
  } else {
    // 新建时的默认值
    Object.assign(formData, {
      name: '',
      description: '',
      department: '',
      type: 'initial',
      status: 'active',
      isDefault: false,
      content: {
        chiefComplaint: '',
        presentIllness: '',
        pastHistory: '',
        allergyHistory: '',
        physicalExam: '',
        labResults: '',
        diagnosis: '',
        treatmentPlan: '',
        medicalAdvice: ''
      }
    })
  }
}

const insertVariable = (variable) => {
  const variableText = `{{${variable}}}`
  const activeSection = currentActiveSection.value
  
  if (formData.content[activeSection]) {
    formData.content[activeSection] += variableText
  } else {
    formData.content[activeSection] = variableText
  }
  
  showAllVariables.value = false
  ElMessage.success(`已插入变量: ${variable}`)
}

const clearSection = (section) => {
  formData.content[section] = ''
  ElMessage.info(`已清空${getSectionName(section)}内容`)
}

const getSectionName = (section) => {
  const sectionMap = {
    chiefComplaint: '主诉',
    presentIllness: '现病史',
    pastHistory: '既往史',
    allergyHistory: '过敏史',
    physicalExam: '体格检查',
    labResults: '辅助检查',
    diagnosis: '诊断',
    treatmentPlan: '治疗方案',
    medicalAdvice: '医嘱'
  }
  return sectionMap[section] || section
}

const formatPreviewText = (text) => {
  if (!text) return ''
  
  // 替换变量为示例值
  return text
    .replace(/{{patient\.name}}/g, '张三')
    .replace(/{{patient\.age}}/g, '35')
    .replace(/{{patient\.gender}}/g, '男')
    .replace(/{{patient\.phone}}/g, '138****1234')
    .replace(/{{patient\.idCard}}/g, '110101198901011234')
    .replace(/{{current\.date}}/g, '2024-03-20')
    .replace(/{{current\.time}}/g, '14:30:00')
    .replace(/{{doctor\.name}}/g, '张医生')
    .replace(/{{department\.name}}/g, '内科')
    .replace(/{{hospital\.name}}/g, '智医云联医院')
}

const refreshPreview = () => {
  ElMessage.info('预览已刷新')
}

const handleSave = async () => {
  if (!basicFormRef.value) return

  try {
    // 验证基本信息表单
    await basicFormRef.value.validate()
    
    // 检查模板内容是否为空
    if (!hasContent.value) {
      ElMessage.warning('请至少填写一个模板内容字段')
      return
    }

    saving.value = true
    
    // TODO: 调用API保存模板
    // if (props.isEdit) {
    //   await templateApi.update(props.templateData.id, formData)
    // } else {
    //   await templateApi.create(formData)
    // }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(props.isEdit ? '模板更新成功' : '模板创建成功')
    emit('saved', { ...formData })
  } catch (error) {
    if (error && error.fields) {
      ElMessage.warning('请完善基本信息')
    } else {
      ElMessage.error(props.isEdit ? '模板更新失败' : '模板创建失败')
    }
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 监听文本区域焦点，设置当前活动区域
const setActiveSection = (section) => {
  currentActiveSection.value = section
}

// 初始化
initFormData()

// 监听模板数据变化
watch(() => props.templateData, () => {
  initFormData()
}, { deep: true })
</script>

<style lang="scss" scoped>
.template-edit {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
  
  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
  }
}

.edit-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  align-items: start;
}

.basic-info-card,
.content-editor-card,
.preview-card {
  grid-column: 1 / -1;
}

.content-editor-card,
.preview-card {
  grid-column: span 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.switch-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.content-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.content-editor {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.editor-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    
    h4 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.preview-content {
  .preview-section {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    h5 {
      margin: 0 0 8px 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      padding-bottom: 4px;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .preview-text {
      color: #606266;
      line-height: 1.6;
      white-space: pre-wrap;
      background: #f8f9fa;
      padding: 12px;
      border-radius: 4px;
      border-left: 4px solid #409eff;
    }
  }
}

.empty-preview {
  text-align: center;
  padding: 40px 0;
}

.variables-dialog {
  :deep(.el-table) {
    .el-table__row {
      cursor: pointer;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .edit-content {
    grid-template-columns: 1fr;
  }
  
  .content-editor-card,
  .preview-card {
    grid-column: 1 / -1;
  }
}

:deep(.el-textarea) {
  textarea {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>